package com.leetroll.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leetroll.api.mapper.OrderMapper;
import com.leetroll.api.service.OrderDetailService;
import com.leetroll.api.service.OrderService;
import com.leetroll.common.constant.SQLConstant;
import com.leetroll.common.entity.*;
import com.leetroll.common.enums.EOrderStatus;
import com.leetroll.common.enums.EPayChannel;
import com.leetroll.common.vo.OrderDetailVO;
import com.leetroll.common.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> implements OrderService {

    private final OrderDetailService orderDetailService;

    @Autowired
    public OrderServiceImpl(OrderDetailService orderDetailService) {
        this.orderDetailService = orderDetailService;
    }

    @Override
    public List<OrderVO> listByUserId(Long userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.USER_ID, userId);
        List<Order> orderList = this.list(queryWrapper);
        List<OrderVO> orderVOS = new ArrayList<>();
        orderList.forEach(order -> {
            List<OrderDetailVO> orderDetailVOS = orderDetailService.listByOrderId(order.getId());
            orderVOS.add(new OrderVO(order, orderDetailVOS));
        });
        return orderVOS;
    }

    @Override
    public List<OrderVO> listByUserAndStatus(Long userId, String status) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.USER_ID, userId);
        if (status.equals("ongoing")) {
            queryWrapper.in(SQLConstant.ORDER_STATUS, Arrays.asList(EOrderStatus.OPEN.getStatus(), EOrderStatus.FAIL.getStatus()));
        } else {
            queryWrapper.eq(SQLConstant.ORDER_STATUS, EOrderStatus.CLOSED.getStatus());
        }
        List<Order> orderList = this.list(queryWrapper);
        List<OrderVO> orderVOS = new ArrayList<>();
        orderList.forEach(order -> {
            List<OrderDetailVO> orderDetailVOS = orderDetailService.listByOrderId(order.getId());
            orderVOS.add(new OrderVO(order, orderDetailVOS));
        });
        return orderVOS;
    }

    @Override
    public Order getByBatchCode(String batchCode) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.ORDER_BATCH_CODE, batchCode);
        return this.getOne(queryWrapper);
    }

    @Override
    @Transactional
    public Order addOrder(Long userId, List<OrderDetailVO> cartItemVOS) {
        //生成订单
        Order order = new Order();
        order.setBatchCode(UUID.randomUUID().toString());
        order.setUserId(userId);
        order.setPayChannel(EPayChannel.WEPAY.getChannel());
        order.setStatus(EOrderStatus.OPEN.getStatus());
        order.setBody(cartItemVOS.stream().map(OrderDetailVO::getName).collect(Collectors.joining(";")));
        order.setTotalPrice(cartItemVOS.stream().mapToDouble(OrderDetailVO::getPrice).sum());
        order.insert();
        //生成订单明细 order_detail
        List<OrderDetail> details = new ArrayList<>();
        cartItemVOS.forEach(cartItemVO -> {
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(order.getId());
            detail.setItemId(cartItemVO.getItemId());
            detail.setPrice(cartItemVO.getPrice());
            detail.setActualPrice(cartItemVO.getActualPrice());
            details.add(detail);
        });
        orderDetailService.saveBatch(details);
        return order;
    }

    @Override
    public Order updateOrder(Order order) {
        order.setBatchCode(UUID.randomUUID().toString());
        order.setPayChannel(order.getPayChannel());
        order.updateById();
        return order;
    }

    @Override
    public boolean paySuccess(String batchCode, String payCode, String payTime) {
        Order order = getByBatchCode(batchCode);
        if (order == null || order.getStatus().equals(EOrderStatus.CLOSED.getStatus())) {
            return true;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(); // 进行日期转换
        try {
            date = sdf.parse(payTime);
        } catch (ParseException e) {
            log.error("parse pay time error: {}", e.getMessage());
        }

        order.setStatus(EOrderStatus.CLOSED.getStatus());
        order.setPayCode(payCode);
        order.setPayTime(date);
        order.updateById();

        return true;
    }

    @Override
    public boolean checkIfUserOwnItem(Long userId, Integer itemId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.USER_ID, userId);
        queryWrapper.eq(SQLConstant.ORDER_STATUS, EOrderStatus.CLOSED.getStatus());
        List<Long> orderIds = this.list(queryWrapper).stream().map(Order::getId).collect(Collectors.toList());

        OrderDetail detail = orderDetailService.getByOrderIdAndItemId(orderIds, itemId);

        return detail != null;
    }
}
